﻿Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Linq
Imports TNCDAL
Imports System.Text
Imports System.Text.RegularExpressions
Imports TNCBAL
Imports HTLibrary
Public Class ucAdvanceVoucherNew
    Inherits System.Windows.Forms.UserControl
    Dim mamV As New MAdvanceVoucher
    Dim mfile As New MFiles
    Dim uti As New Utilities
    Dim _id_filefee As Integer
    Dim _arrayFileFee As ArrayList
    Dim _price As Double
    Dim _isNew As Boolean = False
    Dim _isEdit As Boolean = False
    Dim isdatacbContFile = False
    Private _arrayFileCont As New ArrayList
    Private _arrrayFileCurrency As New ArrayList
    Private _arrayFee As New ArrayList
    Dim dtFee As New DataTable
    Dim isFile As Boolean
    Dim isApprove As Boolean = False
    Dim editRowIndex As Integer = 0
    Dim id_current_user As Integer = 0
    Dim id_file As Integer = 0

    Public Sub New(ByVal id_FileFee As Integer, ByVal price As Double)
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        DataGridViewHelper.DataGridView_InitEvent(gridDetail)
        _id_filefee = id_FileFee
        _price = price
    End Sub
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        DataGridViewHelper.DataGridView_InitEvent(gridDetail)
        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Public Sub New(ByVal arrayFileFee As ArrayList, ByVal price As Double)
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(grid)
        DataGridViewHelper.DataGridView_InitEvent(gridDetail)
        _arrayFileFee = arrayFileFee
        _price = price
        txtAmount.Text = price
    End Sub
    Private Sub BindingDataToGrid()

        Dim source As New BindingSource
        Dim query = mamV.GetVoucherList()
        source.DataSource = query
        grid.DataSource = source
        BindingNavigator1.BindingSource = source

        grid.Columns(0).Visible = False
        grid.Columns(4).Visible = False
        grid.Columns(6).Visible = False
        'grid.Columns(9).Visible = False
        EnableControls(False)
        Try
            FormatGridDetail()
        Catch ex As Exception

        End Try
 
        'grid.Rows(editRowIndex).Selected = True
    End Sub
    Private Sub BindingDataToGridSearch(ByVal idFile As Integer)

        Dim source As New BindingSource
        Dim query = mamV.GetVoucherListSearch(idFile)
        source.DataSource = query
        grid.DataSource = source
        BindingNavigator1.BindingSource = source

        grid.Columns(0).Visible = False
        grid.Columns(4).Visible = False
        grid.Columns(6).Visible = False
        'grid.Columns(9).Visible = False
        'EnableControls(False)
        'FormatGridDetail()
        'grid.Rows(editRowIndex).Selected = True
    End Sub
    Private Sub LoadImport()

        'Load advancevoucher
        uti.FillAllUserCombo(cbTreeAdvanceUser)
        'uti.FillAllFileForAdvancedComboTree(cbTreeFile, chkExportFile.Checked)
        uti.FillAllFileForAdvancedTextbox(txtFile, chkExportFile.Checked)
        'uti.FillAllFileForAdvancedComboTree(cbTreeFileSearch, chkExportFileSearch.Checked)
        treeFee.Nodes.Clear()
        uti.FillFeeTree(treeFee, 1)
        isdatacbContFile = True
        ' cbFileCont.SelectedIndex = 0
        dateAdvance.Value = DateTime.Now()
        dtFee.Columns.Add("IDFileFee")
        dtFee.Columns.Add("IDFile")
        dtFee.Columns.Add("IDFee")
        dtFee.Columns.Add("FeeName")
        dtFee.Columns.Add("Price")


    End Sub
    Private Sub FormatGrid()
        'Hiển thị grid
        grid.Columns(3).DefaultCellStyle.Format = "#,##0.##"
        grid.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    End Sub
    Private Sub FormatGridDetail()
        gridDetail.Columns(4).DefaultCellStyle.Format = "#,##0.##"
        gridDetail.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    End Sub
    Private Sub EnableControls(ByVal v As Boolean)

        dateAdvance.Enabled = v
        dateAdvance.BackColor = Color.White
        'txtAdvanceNo.Enabled = v
        cbTreeAdvanceUser.Enabled = v
        '    cbTreeFile.ForeColor = Color.White
        txtDescription.Enabled = v
        ' txtDescription.ForeColor = Color.White
        chkExportFile.Enabled = v
        '   chkExportFile.ForeColor = Color.White
        'cbTreeFile.Enabled = v
        txtFile.Enabled = v
        '  cbTreeFile.ForeColor = Color.White

        treeFee.Enabled = v
        'treeFee.ForeColor = Color.White
        'txtInvoiceNo.Enabled = v
        If _isEdit Then
            txtFile.Enabled = Not v
            'cbTreeFile.Enabled = Not v
        End If

        If _isNew Then
            txtID_AdvanceVoucher.Text = 0
            dateAdvance.Value = DateTime.Now()
            txtAdvanceNo.Text = ""
            cbTreeAdvanceUser.SelectedIndex = 0

            txtDescription.Text = ""
            txtAmount.Text = 0

            gridDetail.DataSource = Nothing
            txtNguoiLapPhieu.Text = GeneralClassBAL._User.FullName
            '  txtInvoiceNo.Text = ""
            btnOk.Enabled = v
        End If


    End Sub
    Private Sub ResetControl()
        'uti.FillAllFileForAdvancedComboTree(cbTreeFile, chkExportFile.Checked)
        uti.FillAllFileForAdvancedTextbox(txtFile, chkExportFile.Checked)
        txtID_AdvanceVoucher.Text = 0
        dateAdvance.Value = DateTime.Now()
        txtAdvanceNo.Text = ""
        'cbTreeFile.SelectedIndex = 0
        cbTreeAdvanceUser.SelectedIndex = 0
        txtDescription.Text = ""
        txtAmount.Text = 0

        gridDetail.DataSource = Nothing
        txtNguoiLapPhieu.Text = GeneralClassBAL._User.FullName
    End Sub

    Private Sub grid_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grid.RowEnter
        'Load vào các textbox

        Dim rw As Integer = e.RowIndex
        Dim dg As DataGridView = CType(sender, DataGridView)
        txtID_AdvanceVoucher.Text = dg.Item(0, rw).Value   'row.Item("id").ToString
        If dg.Item(1, rw).Value IsNot Nothing Then
            dateAdvance.Value = CType(dg.Item(1, rw).Value.ToString(), DateTime)
        End If
        txtAdvanceNo.Text = dg.Item(2, rw).Value
        txtAmount.Text = dg.Item(3, rw).Value

        If dg.Item(4, rw).Value IsNot Nothing Then
            cbTreeAdvanceUser.SelectedValue = CInt(dg.Item(4, rw).Value)
        End If
        id_current_user = dg.Item(6, rw).Value
        txtNguoiLapPhieu.Text = dg.Item(7, rw).Value

        'If dg.Item(8, rw).Value IsNot Nothing Then
        isApprove = CBool(dg.Item(11, rw).Value)
        'End If

        txtDescription.Text = dg.Item(8, rw).Value
        'Lấy thông tin File đi kèm với phiếu tạm ứng 
        Try
            'cbTreeFile.SelectedValue = mamV.GetIDFileOfAdvance(txtID_AdvanceVoucher.Text)
            id_file = mamV.GetIDFileOfAdvance(txtID_AdvanceVoucher.Text)
            'Lấy thông tin file là export hay support
            chkExportFile.Checked = mfile.getFileType(id_file)
            txtFile.Text = mfile.getFileNoFile(id_file)
        Catch ex As Exception
            'MessageBox.Show("File không tồn tại")
        End Try
        Dim query = mamV.GetListDetailFee(Me.txtID_AdvanceVoucher.Text)


        If query IsNot Nothing Then
            gridDetail.DataSource = query
            gridDetail.Columns(0).Visible = False
            gridDetail.Columns(1).Visible = False
            gridDetail.Columns(2).Visible = False
        Else
            grid.DataSource = Nothing
        End If

        txtNguoiLapPhieu.Text = GeneralClassBAL._User.UserName

    End Sub


    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        _isNew = True
        _isEdit = False
        grid.Enabled = False
        EnableControls(True)
        btnSave.Enabled = True
        btncancel.Enabled = True
        btnEdit.Enabled = False
        btnDelete.Enabled = False
        btnAdd.Enabled = False
        chkSearch.Enabled = False
        treeFee.Enabled = True

        'Load lại combo File để tạm ứng 
        'uti.FillAllFileForAdvancedComboTree(cbTreeFile, chkExportFile.Checked)

        If chkExportFile.Checked = True Then
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/EX"

        Else
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/IM"

        End If

        'Load thông tin vào treeFee
        treeFee.Nodes.Clear()
        uti.FillFeeTree(treeFee, 1, id_file)
        treeFee.ExpandAll()
        'If treeFee.Nodes.Count = 1 Then
        '    MessageBox.Show("Tất cả các phí của file hiện tại đã được tạm ứng")

        'End If

        btnOk.Enabled = True
        'Lấy số tự động
        Dim pNo As Integer = mamV.GetLastedAdvanceNo()

        If pNo = 0 Then
            txtAdvanceNo.Text = 1 & "/TU"

        Else
            txtAdvanceNo.Text = pNo + 1 & "/TU"
        End If
        grid.Enabled = False
        editRowIndex = 0
        dateAdvance.Value = DateTime.Now
        dateAdvance.Focus()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        ''Chỉ cho phép sửa các phiếu nào chưa approve

        'Nếu đã approve thì k được phép sửa
        grid.Enabled = False
        If isApprove = True Then
            MessageBox.Show("Voucher is approved. Don't allow edit")
            Return
        End If
        editRowIndex = grid.CurrentRow.Index
        _isEdit = True
        _isNew = False
        EnableControls(True)
        btnSave.Enabled = True
        btncancel.Enabled = True
        btnEdit.Enabled = False
        btnDelete.Enabled = False
        btnAdd.Enabled = False
        treeFee.Enabled = False
        chkSearch.Enabled = False
        gridDetail.ReadOnly = False
        'Khi sửa thì k cho thêm phí, chỉ cho sửa số tiền
        btnOk.Enabled = False
        dateAdvance.Focus()
        'Load danh sách file đã có tạm ứng rồi
        'uti.FillAllFileForAdvancedComboTree(cbTreeFile, chkExportFile.Checked)
        Try
            'cbTreeFile.SelectedValue = mamV.GetIDFileOfAdvance(txtID_AdvanceVoucher.Text)

        Catch ex As Exception
            'MessageBox.Show("File không tồn tại")
        End Try
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

            If txtAdvanceNo.Text = "" Then
                MessageBox.Show("Chưa nhập số phiếu tạm ứng")
                txtAdvanceNo.Focus()
                Return
            End If

            If gridDetail.RowCount <= 0 Then
                MessageBox.Show("Chưa nhập phí tạm ứng")
                treeFee.Focus()
                Return
            End If
        Try
            If CDbl(txtAmount.Text) = 0 Then
                MessageBox.Show("Chưa nhập số tiền muốn tạm ứng")
                gridDetail.Focus()
                Return
            End If
        Catch ex As Exception

        End Try
           

        If _isNew Then
         Dim obj As New tblAdvanceVoucher

                'If chkTU.Checked = True Then
                '    obj.ID_AdvanceVoucher = cbAdvanceVoucher.SelectedValue
                'End If

                obj.CreatedDate = dateAdvance.Value.ToShortDateString()
                obj.AdvanceVoucherNo = txtAdvanceNo.Text
                obj.Description = txtDescription.Text
                obj.ID_AdvanceUser = cbTreeAdvanceUser.SelectedValue
                obj.Amount = Double.Parse(txtAmount.Text.Replace(".", ""))
                obj.IsApprove = False
                obj.ID_User = GeneralClassBAL._User.ID_User

                ' obj.InvoiceNo = txtInvoiceNo.Text
                mamV.InsertNewRecord(obj)
                'Sau khi thêm xong thì lấy giá trị idAdvacne mới để thêm vào file feee
                Dim id_adV As Integer = 0
                id_adV = mamV.getIDNewAdvanceVoucher()
                'update vào file fee
                'Với mỗi file 


                'Đang tính theo file
                'For Each id_f As Integer In _arrayFileCont
                'For Each id_ff As Integer In _arrayFee
                '    Dim objff As New tblFileFee
                '    objff.ID_File = id_f
                '    objff.ID_AdvanceVoucher = id_adV
                '    objff.ID_Fee = id_ff
                '    Dim mbr As New MBuyingRate
                '    mbr.InsertNewRecord(objff)
                'Next
                'duyệt qua bảng chi tiết phí, láy tiền chia đều cho số lượng file

                For index = 0 To gridDetail.Rows.Count - 1
                    'Dim mbr As New MBuyingRate
                    ''Lấy id của phí cần tạm ứng
                    'Dim idFee = CInt(gridDetail.Rows(index).Cells(0).Value)
                    ''Tìm ra idFileFee của phí này đi kèm với file
                    'Dim idFileFee = CInt(mbr.GetIDFileFeeOfFile(idFee, cbTreeAdvanceUser.SelectedValue))

                    'Sửa số tiền chứ k cho thêm


                    Dim objff As New tblFileFee
                objff.ID_File = id_file 'cbTreeFile.SelectedValue
                    objff.ID_AdvanceVoucher = id_adV
                    objff.ID_Fee = CInt(gridDetail.Rows(index).Cells(2).Value)

                    If gridDetail.Rows(index).Cells(4).Value = "" Then
                        objff.Price = 0
                    Else
                        objff.Price = CDbl(gridDetail.Rows(index).Cells(4).Value)

                    End If


                Dim mbr As New MBuyingRate
                If objff.Price <> 0 Then
                    mbr.InsertNewRecord(objff)
                End If

                Next

        
        End If


            If _isEdit Then
            If GeneralClassBAL._User.UserName = txtNguoiLapPhieu.Text.Trim() Then

                'sửa chi tiết trước rồi mới sửa đầu phiếu
                For index = 0 To gridDetail.Rows.Count - 1

                    Dim objff As New tblFileFee
                    objff.ID_FileFee = CInt(gridDetail.Rows(index).Cells(0).Value)

                    If gridDetail.Rows(index).Cells(4).Value.ToString = "" Then
                        objff.Price = 0
                    Else
                        objff.Price = CDbl(gridDetail.Rows(index).Cells(4).Value)

                    End If

                    Dim mbr As New MBuyingRate
                    mbr.UpdatePrice2(objff)
                Next
                'Lưu thông tin đầu phiếu có sửa chữa
                Dim obj As New tblAdvanceVoucher
                obj.ID_AdvanceVoucher = txtID_AdvanceVoucher.Text

                obj.CreatedDate = dateAdvance.Value.ToShortDateString()
                obj.AdvanceVoucherNo = txtAdvanceNo.Text
                obj.Description = txtDescription.Text
                obj.ID_AdvanceUser = cbTreeAdvanceUser.SelectedValue
                obj.Amount = Double.Parse(txtAmount.Text.Replace(".", ""))
                obj.IsApprove = False 'chkApprove.Checked
                obj.ID_User = GeneralClassBAL._User.ID_User

                mamV.UpdateRecord(obj)

                'Next
            Else
                MessageBox.Show("You have not the right to edit this payment voucher")
                Return
            End If
        End If

            ' End If
            _isNew = False
            _isEdit = False
            _id_filefee = False

            'LabelX2.Visible = False
            btnAdd.Enabled = True
            btnEdit.Enabled = True
            btnDelete.Enabled = True
            btnSave.Enabled = False
        btncancel.Enabled = False
        chkSearch.Enabled = True
            EnableControls(False)
            btnOk.Enabled = False
            BindingDataToGrid()
            grid.Enabled = True
            grid.Rows(editRowIndex).Selected = True
            grid.FirstDisplayedScrollingRowIndex = editRowIndex
            grid.CurrentCell = grid(1, editRowIndex)
     
    End Sub


    ''' <summary>
    ''' HT Code: Print Advance Voucher
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btPrint.Click
        CViewer.PrintReport_AdvanceVoucher(Integer.Parse(txtID_AdvanceVoucher.Text))
    End Sub


    Private Function GetCheck(ByVal node As TreeNodeCollection) As List(Of TreeNode)
        Dim lN As New List(Of TreeNode)
        For Each n As TreeNode In node

            If Not n.Text = "Check All" Then
                If n.Checked Then lN.Add(n)
            End If

            lN.AddRange(GetCheck(n.Nodes))
        Next

        Return lN
    End Function



    Private Sub cbFileCont_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Sau khi chọn file thì sẽ hiển thị chọn cont

        If isdatacbContFile = True Then


            treeFee.Nodes.Clear()

            uti.FillFeeTree(treeFee, 3)
            'Load phí vận chuyển 

        End If

    End Sub



    Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click
        _isEdit = False
        _isNew = False
        btnAdd.Enabled = True
        btnEdit.Enabled = True
        btnDelete.Enabled = True
        btnSave.Enabled = False
        btncancel.Enabled = False
        chkSearch.Enabled = True
        BindingDataToGrid()
        EnableControls(False)
        btnOk.Enabled = False
        grid.Enabled = True
    End Sub

    Private Sub ucAdvanceVoucher_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadImport()
        BindingDataToGrid()

    End Sub

    Private Sub gridDetail_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridDetail.CellEndEdit
        If (e.ColumnIndex = 4) Then
            'Format tiền

            If _isNew = True Then
                'gridDetail.Columns(4).DefaultCellStyle.Format = "#,##0.##"

                gridDetail.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = uti.FormatMoney(gridDetail.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
            End If

            'cập nhật lại tổng
            CalculateTotalBuying()
        End If
    End Sub
    Private Sub CalculateTotalBuying()
        Dim gridTinhTong As DevComponents.DotNetBar.Controls.DataGridViewX
        gridTinhTong = gridDetail
        'Luôn là giá tiền Việt cần phải đổi theo tỉ giá nằm trong file

        Dim total As Double = 0
        For i As Integer = 0 To gridTinhTong.Rows.Count
            Try
                Dim price As Double

                price = Double.Parse(gridTinhTong.Rows(i).Cells(4).Value.ToString)
                total += price
            Catch ex As Exception

            End Try
        Next
        txtAmount.Text = total
    End Sub

 

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If GeneralClassBAL._User.ID_User = id_current_user Then


            If isApprove = True Then
                MessageBox.Show("Advance Voucher is approved. Don't allow delete")
                Return
            End If

            Try
                If (MessageBox.Show("Do you really want to delete" & txtAdvanceNo.Text & " voucher record?",
                                   "Delete Warning", MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, False) = DialogResult.Yes) Then

                    Dim id As Integer = CInt(txtID_AdvanceVoucher.Text)

                    If id > 0 Then
                        'Cập nhật lại thông tin cho các phí có nó
                        Dim mb As New MBuyingRate
                        mb.DeleteRecordHasAdvance(id)
                        mamV.DeleteRecord(id)
                        BindingDataToGrid()

                        If grid.Rows.Count <= 0 Then
                            gridDetail.DataSource = Nothing
                            txtAmount.Text = ""

                            txtAdvanceNo.Text = ""
                            txtDescription.Text = ""
                            cbTreeAdvanceUser.SelectedValue = 0
                        End If

                        EnableControls(False)
                    End If
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            'Xóa


        Else
            MessageBox.Show("You have not the right to delete this payment voucher")
            Return
        End If


    End Sub

    'Private Sub grid_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grid.CellDoubleClick
    '    Dim uc As New ucDetailFeeAdvance(txtID_AdvanceVoucher.Text)
    '    frmMain.AddNewDockContainerItem("DetailFee", "Detail Fee of " & txtAdvanceNo.Text, uc)
    'End Sub
    ' Updates all child tree nodes recursively.
    Private Sub CheckAllChildNodes(ByVal treeNode As TreeNode, ByVal nodeChecked As Boolean)
        Dim node As TreeNode
        For Each node In treeNode.Nodes
            node.Checked = nodeChecked
            If node.Nodes.Count > 0 Then
                ' If the current node has child nodes, call the CheckAllChildsNodes method recursively.
                Me.CheckAllChildNodes(node, nodeChecked)
            End If
        Next node
        'treeNode.Checked = False
    End Sub

    ' NOTE   This code can be added to the BeforeCheck event handler instead of the AfterCheck event.
    ' After a tree node's Checked property is changed, all its child nodes are updated to the same value.
    Private Sub treeFee_AfterCheck(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles treeFee.AfterCheck
        ' The code only executes if the user caused the checked state to change.
        If e.Action <> TreeViewAction.Unknown Then
            If e.Node.Nodes.Count > 0 Then
                ' Calls the CheckAllChildNodes method, passing in the current 
                ' Checked value of the TreeNode whose checked state changed. 
                Me.CheckAllChildNodes(e.Node, e.Node.Checked)
            End If
        End If
    End Sub


    Private Sub btnReceiptVoucher_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReceiptVoucher.Click
        Dim db As New TanNamChinhDataContext
        Dim ID_AdvanceVoucher As Integer
        ID_AdvanceVoucher = txtID_AdvanceVoucher.Text
        Dim obj_AV = (From p In db.tblAdvanceVouchers
                     Where p.ID_AdvanceVoucher = ID_AdvanceVoucher
                     Select p).SingleOrDefault

        Dim uc As New ucReceiptVouchersNew(obj_AV)
        frmMain.AddNewDockContainerItem("Receipt Vouchers", "Receipt Vouchers", uc)

    End Sub

    Private Sub chkExportFile_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkExportFile.CheckedChanged
        uti.FillAllFileForAdvancedTextbox(txtFile, chkExportFile.Checked)
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click

        If _isNew Then
            'Đang chọn phí của lô hàng
            _arrayFee.Clear()
            Dim row1 As DataRow
            dtFee.Clear()

            For Each n As TreeNode In GetCheck(treeFee.Nodes)
                ' MessageBox.Show(n.Name, n.Text)
                'Có danh sách các phí thì tính tổng tiền và in ra phiếu chi
                _arrayFee.Add(n.Name)
                '   totalPrice += mBR.getPriceFollowFee(n.Name)
                row1 = dtFee.NewRow
                row1.Item("IDFileFee") = 0
                row1.Item("IDFile") = id_file 'cbTreeFile.SelectedValue
                row1.Item("IDFee") = n.Name
                row1.Item("FeeName") = n.Text
                row1.Item("Price") = Double.Parse(0)

                dtFee.Rows.Add(row1)

                '    a.ID_FileFee,
                'a.ID_File,
                'a.ID_Fee,
                'Fee = If(a.tblFee IsNot Nothing, a.tblFee.FeeName, String.Empty),
                'a.Price

            Next
            gridDetail.DataSource = dtFee
            gridDetail.Columns(0).Visible = False
            gridDetail.Columns(1).Visible = False
            gridDetail.Columns(2).Visible = False
            gridDetail.Columns(3).ReadOnly = True

            'If gridDetail.RowCount > 0 Then
            '    'gridDetail.Columns(2).ReadOnly = False
            '    FormatGridDetail()
            'End If


        Else
            'Nếu là sửa phí
            'Add vào dt thêm các thông tin 
            'Dim query = mamV.GetListDetailFee(Me.txtID_AdvanceVoucher.Text)

        
        End If

        gridDetail.Focus()

    End Sub

   

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        BindingDataToGrid()
    End Sub

    Private Sub grid_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles grid.DataBindingComplete
        'uti.FillAllFileForAdvancedComboTree(cbTreeFile, chkExportFile.Checked)

        If grid.RowCount > 0 Then
            btnEdit.Enabled = True
            btnDelete.Enabled = True
            FormatGrid()
        Else
            'Reset các textboxt và combox
            ResetControl()
            btnEdit.Enabled = False
            btnDelete.Enabled = False
        End If
        'Set màu cho dòng nào bị chậm

        For index As Integer = 0 To grid.RowCount - 1
            'Kiểm tra

            If mamV.IsAdvanceDelay(uti.GetTime_HangTau, grid.Rows(index).Cells(0).Value) = True Then
                'Bị chậm
                grid.Rows(index).DefaultCellStyle.ForeColor = Color.Red

            End If

        Next
        'Lấy thông tin File đi kèm với phiếu tạm ứng 
        Try
            If txtID_AdvanceVoucher.Text <> "0" Then
                'cbTreeFile.SelectedValue = mamV.GetIDFileOfAdvance(txtID_AdvanceVoucher.Text)
                id_file = mamV.GetIDFileOfAdvance(txtID_AdvanceVoucher.Text)
                txtFile.Text = mfile.getFileNoFile(id_file)
            End If

        Catch ex As Exception
            'MessageBox.Show("File không tồn tại")
        End Try
    End Sub

    Private Sub gridDetail_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles gridDetail.DataBindingComplete

        If gridDetail.RowCount > 0 Then
            FormatGridDetail()
        End If

    End Sub

    Private Sub txtAmount_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmount.KeyPress
        e.Handled = True
    End Sub

    Private Sub txtAmount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.TextChanged
        uti.FormatCurr(txtAmount)
    End Sub

    Private Sub treeFee_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles treeFee.KeyPress
        If e.KeyChar = Convert.ToChar(Keys.Enter) Then
            If _isNew Then
                'Đang chọn phí của lô hàng
                _arrayFee.Clear()
                Dim row1 As DataRow
                dtFee.Clear()

                For Each n As TreeNode In GetCheck(treeFee.Nodes)
                    ' MessageBox.Show(n.Name, n.Text)
                    'Có danh sách các phí thì tính tổng tiền và in ra phiếu chi
                    _arrayFee.Add(n.Name)
                    '   totalPrice += mBR.getPriceFollowFee(n.Name)
                    row1 = dtFee.NewRow
                    row1.Item("IDFileFee") = 0
                    row1.Item("IDFile") = id_file
                    row1.Item("IDFee") = n.Name
                    row1.Item("FeeName") = n.Text
                    row1.Item("Price") = Double.Parse(0)

                    dtFee.Rows.Add(row1)

                    '    a.ID_FileFee,
                    'a.ID_File,
                    'a.ID_Fee,
                    'Fee = If(a.tblFee IsNot Nothing, a.tblFee.FeeName, String.Empty),
                    'a.Price

                Next
                gridDetail.DataSource = dtFee
                gridDetail.Columns(0).Visible = False
                gridDetail.Columns(1).Visible = False
                gridDetail.Columns(2).Visible = False
                gridDetail.Columns(3).ReadOnly = True

                'If gridDetail.RowCount > 0 Then
                '    'gridDetail.Columns(2).ReadOnly = False
                '    FormatGridDetail()
                'End If


            Else
                'Nếu là sửa phí
                'Add vào dt thêm các thông tin 
                Dim query = mamV.GetListDetailFee(Me.txtID_AdvanceVoucher.Text)


            End If

            gridDetail.Focus()
            e.Handled = True
        End If

    End Sub

    Private Sub cbTreeFile_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        e.Handled = True
    End Sub

   
    Private Sub cbTreeFile_TextChanged(sender As System.Object, e As System.EventArgs)

        If chkExportFile.Checked = True Then
            'File xuất
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/EX"

        Else
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/IM"

        End If

        'Kiểm tra xem thử file muốn tạm ứng có phí nào được tạm ứng chưa, nếu có rồi thì loại ra k load vào
        treeFee.Nodes.Clear()
        uti.FillFeeTree(treeFee, 1, id_file)
        treeFee.ExpandAll()
        Dim childNode = treeFee.Nodes(0).Nodes
        If _isNew And childNode.Count = 0 Then
            MessageBox.Show("Tất cả các phí của file hiện tại đã được tạm ứng")
        End If

    End Sub

    Private Sub gridDetail_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles gridDetail.EditingControlShowing
        '    RaiseEvent  e.Control.KeyPress -= New KeyPressEventHandler(AddressOf Column1_KeyPress)
        If gridDetail.CurrentCell.ColumnIndex = 4 Then
            'Desired Column
            Dim tb As TextBox = TryCast(e.Control, TextBox)
            If tb IsNot Nothing Then
                AddHandler tb.KeyPress, AddressOf Column1_KeyPress
                'tb.KeyPress += New KeyPressEventHandler(AddressOf Column1_KeyPress)
            End If
        End If
    End Sub
  
    Private Sub Column1_KeyPress(sender As Object, e As KeyPressEventArgs)
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    
    'Private Sub chkExportFileSearch_CheckedChanged(sender As System.Object, e As System.EventArgs)
    '    uti.FillAllFileForAdvancedComboTree(cbTreeFileSearch, chkExportFileSearch.Checked)
    'End Sub

    'Private Sub cbTreeFileSearch_TextChanged(sender As System.Object, e As System.EventArgs)
    '    BindingDataToGridSearch(cbTreeFileSearch.SelectedValue)
    'End Sub

    Private Sub txtFile_Leave(sender As System.Object, e As System.EventArgs) Handles txtFile.Leave
        id_file = mfile.getIDFile(txtFile.Text, chkExportFile.Checked)
        If chkExportFile.Checked = True Then
            'File xuất
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/EX"

        Else
            txtDescription.Text = "Tạm ứng file " & txtFile.Text & "/IM"

        End If

        'Kiểm tra xem thử file muốn tạm ứng có phí nào được tạm ứng chưa, nếu có rồi thì loại ra k load vào
        treeFee.Nodes.Clear()
        uti.FillFeeTree(treeFee, 1, id_file)
        treeFee.ExpandAll()
        Dim childNode = treeFee.Nodes(0).Nodes
        If _isNew And childNode.Count = 0 Then
            MessageBox.Show("Tất cả các phí của file hiện tại đã được tạm ứng")
        End If
    End Sub

    Private Sub chkSearch_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkSearch.CheckedChanged
        If chkSearch.Checked = True Then
            chkExportFile.Enabled = True
            txtFile.Enabled = True
            txtFile.Focus()
        Else
            chkExportFile.Enabled = False
            txtFile.Enabled = False
        End If
    End Sub

    
    Private Sub txtFile_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtFile.KeyDown
        If chkSearch.Checked = True And e.KeyCode = Keys.Enter Then
            BindingDataToGridSearch(mfile.getIDFile(txtFile.Text, chkExportFile.Checked))
        End If
    End Sub
End Class